package com.akxy.pt.tsdb.controller;

import com.akxy.pt.tsdb.domain.stress.StressDataInfo;
import com.akxy.pt.tsdb.influxdb.InfluxDb;
import com.akxy.pt.tsdb.influxdb.operator.FilterOperator;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Mengfly
 */
@RestController
@RequestMapping("/stress")
@Api(tags = "stress")
public class StressController {
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @GetMapping("query")
    public List<StressDataInfo> query(String start,
                                      String end,
                                      String mpId,
                                      int limit) throws ParseException {

        return new InfluxDb()
                .bucket("pt")
                .range(dateFormat.parse(start), dateFormat.parse(end))
                .measurement("stress")
                .filer(new FilterOperator("mp_id", mpId))
                .fieldAsCols()
                .limit(limit, 0)
                .list(StressDataInfo.class);
    }

    @GetMapping("count")
    public Long count(String start,
                      String end,
                      String mpId) throws ParseException {

        return new InfluxDb()
                .bucket("pt")
                .range(dateFormat.parse(start), dateFormat.parse(end))
                .measurement("stress")
                .filer(new FilterOperator("mp_id", mpId))
                .fieldAsCols()
                .count("value");
    }

    @GetMapping("page")
    public Map<String, Object> page(String start, String end,
                                    String mpId, int page, int size) throws ParseException {
        InfluxDb query = new InfluxDb()
                .bucket("pt")
                .range(dateFormat.parse(start), dateFormat.parse(end))
                .measurement("stress")
                .filer(new FilterOperator("mp_id", mpId))
                .fieldAsCols();

        int offset = page * size;

        // 总数目
        long totalCount = query.count("value");

        int pageCount = (int) (totalCount % size == 0 ? totalCount / size : totalCount / size + 1);

        List<StressDataInfo> list = query.limit(size, offset).list(StressDataInfo.class);

        Map<String, Object> pageResult = new HashMap<>();
        pageResult.put("size", size);
        pageResult.put("currentPage", page);
        pageResult.put("totalPage", pageCount);
        pageResult.put("list", list);
        pageResult.put("totalElement", totalCount);
        return pageResult;

    }
}
